using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CsvHelper;
using System.Xml;
using System.IO;

#region "Tutorial Links"
/// http://www.csharp-station.com/Tutorials/lesson17.aspx
/// http://support.microsoft.com/kb/307548
/// http://msdn.microsoft.com/en-us/library/t8t5yhhk.aspx
#endregion
namespace VMC.DataProcessor
{
	
 	public enum ClimateDataOrder 
	{
		Number = 1,
		StationName,
		Temp,
		Wind
	}

	 public class ClimateData
	{
		public int Number {get;set;} 
		public string StationName {get;set;} 
		public int Temp {get;set;} 
		public int Wind {get;set;} 
	}

	
    public class Program
    {
        static void Main(string[] args)
        {
            
            if (args.Count() == 1)
            {
                if (File.Exists(args[0]))
                {
                    string extenstion = args[0].Substring(args[0].Length - 3, 3);
                    if(extenstion.ToUpper() == "CSV")
                    {
                        //1. Read CSV //2. Write XML
                        WriteXMLFile(args[0] + ".xml", ReadCSVFile(args[0]));
                        
                    }
                    else if(extenstion.ToUpper() == "XML")
                    {
                        //1. Read XML //2. Write CSV
                        WriteCSVFile(args[0] + ".csv", ReadXMLFile(args[0]));
                    }
                }
                else
                {
                    Console.WriteLine("Error: {0} file does not exist.", args[0]);
                }
               
            }
            else if (args.Count() > 1)
            {
                Console.WriteLine("Error: Too many arguments provided.");
            }
            else
            {
                Console.WriteLine("Error: Missing input file name.");
            }

            Console.WriteLine("\r\nPress enter to exit...");
            Console.ReadLine();
        }


        private static IEnumerable<ClimateData> ReadCSVFile(string FileName)
        {
            try
            {
                CsvHelper.CsvHelper CSV = new CsvHelper.CsvHelper(File.Open(FileName,FileMode.Open,FileAccess.ReadWrite));
                IEnumerable<ClimateData> items = CSV.Reader.GetRecords<ClimateData>();
                return items;
            }
            catch (Exception Ex)
            {
                Console.WriteLine("Error: Error occured while reading CSV file. \r\n {0} : {1}", Ex.ToString(), Ex.Message);

            }
            return null;
        }

        private static void WriteCSVFile(string FileName, IEnumerable<ClimateData> items)
        {
            try
            {
				if (File.Exists(FileName) == false) File.Create(FileName).Dispose();
                CsvHelper.CsvHelper CSV = new CsvHelper.CsvHelper(File.Open(FileName, FileMode.Open, FileAccess.ReadWrite));
                CSV.Writer.WriteRecords(items);
            }
            catch (Exception Ex)
            {
                Console.WriteLine("Error: Error occured while writing CSV file. \r\n {0} : {1}", Ex.ToString(), Ex.Message);

            }
        }


        private static IEnumerable<ClimateData> ReadXMLFile(string FileName)
        {
            try
            {
                XmlTextReader reader = new XmlTextReader(FileName);
                List<ClimateData> items = new List<ClimateData>();
                ClimateData item = new ClimateData();
                string elename ="";
                while (reader.Read())
                {
                    System.Reflection.PropertyInfo PI;
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element:
                            elename = reader.Name;
                            //Console.WriteLine(elename);
                            if(elename == "Record")
                                item = new ClimateData();
                            break;
                        case XmlNodeType.Text:
                            PI = item.GetType().GetProperty(elename);
                            PI.SetValue(item, Convert.ChangeType(reader.Value, PI.PropertyType) , null);
                            break;
                        case XmlNodeType.EndElement:
                            //Console.WriteLine("/" + reader.Name);
                            if (reader.Name == "Record")
                            {
                                ClimateData inserItem = item;
                                items.Add(inserItem);
                            }
                            break;
                    }

                }
                return items.ToList();
            }
            catch (Exception Ex)
            {
                Console.WriteLine("Error: Error occured while reading XML file. \r\n {0} : {1}", Ex.ToString(), Ex.Message);

            }
            return null;
        }

        //Help Link

 
        private static void WriteXMLFile(string FileName, IEnumerable<ClimateData> items)
        {
            try
            {
                XmlWriter writer = XmlWriter.Create(File.OpenWrite(FileName));
                writer.WriteStartDocument();
                writer.WriteStartElement("Records");
                foreach (ClimateData record in items)
                {
                    writer.WriteStartElement("Record");
                        foreach (int val in Enum.GetValues(typeof(ClimateDataOrder)))
                        {
                            writer.WriteStartElement(Enum.GetName(typeof(ClimateDataOrder), val));
                                System.Reflection.PropertyInfo myPI= record.GetType().GetProperty(Enum.GetName(typeof(ClimateDataOrder), val));
                                writer.WriteString(myPI.GetValue(record, null).ToString());
                            writer.WriteEndElement();       
                        }
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
                writer.WriteEndDocument();
                
                writer.Close();
                //Implement this
            }
            catch (Exception Ex)
            {
                Console.WriteLine("Error: Error occured while writing XML file. \r\n {0} : {1}", Ex.ToString(), Ex.Message);

            }
        }
    }

}
